#ifndef     __COND_VAR_H
#define     __COND_VAR_H

#include "./mutex.h"

namespace rtos {


// FLAG_COND 全局不同重复
template <uint32_t TASK_SIZE, uint32_t FLAG_COND = 0x01>
class CondVar {

public:
    enum class State : uint8_t {
        WAIT_IS_FULL,
        WAKE_UP,
        TIMEOUT,
    };
    
    // true  notify
    // false timeout
    State wait(Mutex &mutex, uint32_t timeout = osWaitForever) {
        if (m_size >= TASK_SIZE) {
            return State::WAIT_IS_FULL;
        }

        m_wait_task[m_size] = osThreadGetId();
        m_size += 1;

        mutex.un_lock();
        uint32_t ret = osThreadFlagsWait(FLAG_COND, osFlagsWaitAny, timeout);
        mutex.lock();
        
        if ((ret & osFlagsError) == 0x00) {
            return State::WAKE_UP;
        }
        return State::TIMEOUT;
    }

    // mutex muse lock
    void notify_all() {
        for (uint32_t i = 0; i < m_size; i ++) {
            osThreadFlagsSet(m_wait_task[i], FLAG_COND);
        }
        m_size = 0;
    }

private:
    osThreadId_t m_wait_task[TASK_SIZE];
    uint32_t m_size = 0;
};

}

#endif
